# -*- coding:utf-8 -*-
import json
from django.shortcuts import render
from web.forms.file import FolderModelForm
from django.forms import model_to_dict
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from web import models
from utils import tencent_cos


def file(request, project_id):
    # 父级目录
    parent_obj = None
    folder_id = request.GET.get('folder', '')

    if folder_id.isdecimal():
        parent_obj = models.FileRepository.objects.filter(id=int(folder_id), file_type=2,
                                                          project=request.tracer.project).first()
    if request.method == 'GET':
        # 路径导航
        breadcrumb_list = []
        parent = parent_obj  # parent是一个文件夹对象
        while parent:  # 一直循环往上级目录查找，直到为根目录
            # breadcrumb_list.insert(0, {'id': parent.id, 'name': parent.name})
            breadcrumb_list.insert(0, model_to_dict(parent, ['id', 'name']))  # 自动生成字典
            parent = parent.parent

        # 文件列表的显示
        queryset = models.FileRepository.objects.filter(project=request.tracer.project)
        if parent_obj:  # 非根目录，已进入其他的目录
            file_obj_list = queryset.filter(parent=parent_obj).order_by('-file_type')
        else:  # 在根目录
            file_obj_list = queryset.filter(parent__isnull=True).order_by('-file_type')

        form = FolderModelForm(request, parent_obj)
        return render(request, 'file.html', locals())

    # 新增或修改文件
    fid = request.POST.get('fid', '')
    edit_obj = None
    if fid.isdecimal():
        edit_obj = models.FileRepository.objects.filter(id=int(fid), file_type=2,
                                                        project=request.tracer.project).first()
    # 修改
    if edit_obj:
        form = FolderModelForm(request, parent_obj, data=request.POST, instance=edit_obj)
    # 新增
    else:
        form = FolderModelForm(request, parent_obj, data=request.POST)

    if form.is_valid():
        form.instance.project = request.tracer.project
        form.instance.file_type = 2
        form.instance.update_user = request.tracer.user
        form.instance.parent = parent_obj
        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


# 删除文件
def file_delete(request, project_id):
    fid = request.GET.get('fid')  # 获取fid
    # 删除数据，级联删除，还要删除cos存储
    delete_obj = models.FileRepository.objects.filter(id=fid, project=request.tracer.project).first()
    if delete_obj.file_type == 1:
        # 删除文件，归还容量空间
        request.tracer.project.use_space -= delete_obj.file_size
        request.tracer.project.save()
        # cos中删除
        tencent_cos.delete_file(request.tracer.project.bucket, request.tracer.project.region, delete_obj.key)
        # 数据库中删除记录
        delete_obj.delete()
        return JsonResponse({'status': True})
    else:
        total_size = 0  # 文件夹总大小
        key_list = []  # 要删除文件的key列表
        folder_list = [delete_obj, ]  # 要删除的文件夹列表
        for folder in folder_list:
            # 拿到该文件夹下所有的文件
            child_list = models.FileRepository.objects.filter(project=request.tracer.project, parent=folder).order_by(
                '-file_size')
            for child in child_list:
                if child.file_type == 2:  # 如果还是文件夹，则将其添加到文件夹列表继续循环
                    folder_list.append(child)
                else:  # 文件则汇总大小，并把key添加到删除列表
                    total_size += child.file_size
                    key_list.append({"Key": child.key})
        # 批量删除文件
        if key_list:
            tencent_cos.delete_file_list(request.tracer.project.bucket, request.tracer.project.region, key_list)
        # 归还容量
        if total_size:
            request.tracer.project.use_space -= total_size
            request.tracer.project.save()
        # 删除数据库记录
        delete_obj.delete()
        return JsonResponse({'status': True})


# 上传文件
@csrf_exempt
def cos_credential(request, project_id):
    per_file_limit = request.tracer.price_policy.per_file_size * 1024 * 1024  # 单个文件上传大小限制
    total_file_limit = request.tracer.price_policy.project_space * 1024 * 1024 * 1024
    total_size = 0
    file_list = json.loads(request.body.decode('utf-8'))  # 前端传过来的数据
    for item in file_list:
        print(item['name'], item['size'])
        if item['size'] > per_file_limit:
            msg = '单个文件最大限制{}M'.format(request.tracer.price_policy.per_file_size)
            return JsonResponse({'status': False, 'error': msg})
        total_size += item['size']
    if request.tracer.project.use_space + total_size > total_file_limit:
        return JsonResponse({'status': False, 'error': '项目剩余容量空间不足，请升级套餐'})

    data_dic = tencent_cos.credential(request.tracer.project.bucket, request.tracer.project.region)
    return JsonResponse({'status': True, 'data': data_dic})


# 将上传文件详情保存到数据库
@csrf_exempt
def file_post(request, project_id):
    print(request.POST)
    return JsonResponse({})
